﻿using System;
using System.Linq;
using Kiva7.Utilities;
using Kiva7.DataResponse;
using Kiva7.DataClasses;

namespace Kiva7.DataRequests
{
    public class LenderJournalEntriesRequest : DataRequest<JournalEntriesResponse, JournalEntry>
    {
        public LenderJournalEntriesRequest()
            : base(true, true)
        {
            DataChanged += Data_CollectionChanged;
        }

        void Data_CollectionChanged(object sender, EventArgs e)
        {
            if (_journalEntryId != 0)
            {
                JournalEntry newSelected = Data.FirstOrDefault(i => i.Id == _journalEntryId);
                if (newSelected != _selected)
                {
                    Selected = newSelected;
                }
            }
        }

        public Uri BuildUri(int loanId, bool includeBulk)
        {
            UrlCreator url = new UrlCreator(string.Format(BaseUrl + "loans/{0}/journal_entries.xml", loanId));
            url.Add("include_bulk", includeBulk);
            url.Add("app_id", KivaAppId);
            return url.ToUri();
        }

        private int _journalEntryId;
        private int _loanId;

        private JournalEntry _selected;
        public JournalEntry Selected
        {
            get { return _selected; }
            private set 
            { 
                _selected = value;
                NotifyPropertyChanged("Selected");
            }
        }

        public void GetJournalEntries(int loanId, bool includeBulk, int journalEntryId)
        {
            _journalEntryId = journalEntryId;
            GetJournalEntries(loanId, includeBulk);
        }

        public void GetJournalEntries(int loanId, bool includeBulk)
        {
            _loanId = loanId;
            base.LoadResponse(BuildUri(loanId, includeBulk));
        }

        public override void DataAdding(JournalEntry o)
        {
            o.LoanId = _loanId;
        }
    }

}
